//
//  hederView.m
//  ZAKER
//
//  Created by dllo on 15/9/28.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "HederView.h"
#import <AVFoundation/AVFoundation.h>
#import "PlayView.h"
#import "MBProgressHUD.h"


@interface HederView ()
{
    BOOL _played;
    NSDateFormatter *_dateFormatter;
}
@property (nonatomic, retain) PlayView *playView;
@property (nonatomic ,retain) AVPlayer *player;
@property (nonatomic, retain) UIProgressView *videoProgress;
@property (nonatomic ,retain) id playbackTimeObserver;
@property (nonatomic, retain) UISlider *videoSlider;
@property (nonatomic, retain) UILabel *timeLabel;
@property (nonatomic, copy) NSString *totalTime;
@property (nonatomic, retain) MBProgressHUD *mb;


@end

@implementation HederView


- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithReuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.videoProgress = [[UIProgressView alloc]init];
        [self.contentView addSubview:self.videoProgress];
        self.playView = [[PlayView alloc]init];
        [self.contentView addSubview:self.playView];
        self.videoSlider = [[UISlider alloc]init];
        [self.contentView addSubview:self.videoSlider];
        self.timeLabel = [[UILabel alloc]init];
        [self.contentView addSubview:self.timeLabel];
        self.stateButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.contentView addSubview:self.stateButton];
           }
    return self;
}


- (void)layoutSubviews
{
    CGFloat offheight = [UIScreen mainScreen].bounds.size.height / 667;
    CGFloat offwidth = [UIScreen mainScreen].bounds.size.width / 375;
    
    [super layoutSubviews];
    self.playView.frame = CGRectMake(10 * offwidth, 5, self.frame.size.width - 20 * offwidth, self.frame.size.height - 40 * offheight);
    self.playView.backgroundColor = [UIColor blackColor];
    
    _stateButton.frame = CGRectMake(0, _playView.frame.size.height + 5, 60 * offwidth , 30 * offheight);
    [_stateButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_stateButton setTitle:@"Play" forState:UIControlStateNormal];
    [_stateButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_stateButton addTarget:self action:@selector(playmovie:) forControlEvents:UIControlEventTouchUpInside];
    
    self.videoSlider.frame = CGRectMake(60 * offwidth, _playView.frame.size.height + 5, self.frame.size.width - 185 * offwidth, 30 * offheight);
    [self.videoSlider addTarget:self action:@selector(videoSlierChangeValue:) forControlEvents:UIControlEventValueChanged];
    [self.videoSlider addTarget:self action:@selector(videoSlierChangeValueEnd:) forControlEvents:UIControlEventTouchUpInside];
    
    self.timeLabel.frame = CGRectMake(265 * offwidth, _playView.frame.size.height + 5, self.frame.size.width - 280 * offwidth, 30 * offheight);
    self.timeLabel.tintColor = [UIColor blackColor];
    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",@"00:00", @"00:00"];
    
    self.videoProgress.frame = CGRectMake(64 * offwidth, _playView.frame.size.height + 19 * offheight, self.frame.size.width - 185 * offwidth, 30 * offheight);
}

- (void)Big:(id)sender
{
    
}


- (void)passDic:(NSString *)urlStr

{
    self.mb = [[MBProgressHUD alloc]initWithFrame:CGRectMake(10, 10, self.playView.frame.size.width, self.playView.frame.size.height)];
    self.mb.labelText = @"正在加载";
    [self.contentView addSubview:_mb];
    [self.mb show:YES];
    NSURL *videoUrl = [NSURL URLWithString:urlStr];
    
    self.playerItem = [AVPlayerItem playerItemWithURL:videoUrl];
    
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    self.playView.player = _player;
    self.stateButton.enabled = NO;
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];
    

}


- (void)moviePlayDidEnd:(NSNotification *)notification {
    NSLog(@"Play end");
    
    
    [self.playView.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
        [self.videoSlider setValue:0.0 animated:YES];
        [self.stateButton setTitle:@"Play" forState:UIControlStateNormal];
    }];
}


- (void)playmovie:(id)sender
{
    if (!_played) {
        [self.playView.player play];
        [self.stateButton setTitle:@"Stop" forState:UIControlStateNormal];
    } else {
        [self.playView.player pause];
        [self.stateButton setTitle:@"Play" forState:UIControlStateNormal];
    }
    _played = !_played;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
            self.stateButton.enabled = YES;
            CMTime duration = self.playerItem.duration;// 获取视频总长度
            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;// 转换成秒
            self.totalTime = [self convertTime:totalSecond];// 转换成播放时间
            [self customVideoSlider:duration];// 自定义UISlider外观
            NSLog(@"movie total duration:%f",CMTimeGetSeconds(duration));
            [self monitoringPlayback:self.playerItem];// 监听播放状态
            [self.mb removeFromSuperview];
            NSLog(@"bofang");
            
        } else if ([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
        NSLog(@"Time Interval:%f",timeInterval);
        CMTime duration = self.playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        if (totalDuration == 0) {
            NSLog(@"stop");
        }
        [self.videoProgress setProgress:timeInterval / totalDuration animated:YES];
    }

}

- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.playView.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}

- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    if (second/3600 >= 1) {
        [[self dateFormatter] setDateFormat:@"HH:mm:ss"];
    } else {
        [[self dateFormatter] setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [[self dateFormatter] stringFromDate:d];
    return showtimeNew;
}


- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    NSLog(@"sss");
    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",@"00:00",_totalTime];
    self.playbackTimeObserver = [self.playView.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;// 计算当前在第几秒
        if (self.videoSlider.value < self.videoProgress.progress) {
            _played = !_played;
            NSLog(@"stop");
            
        }
        [self.videoSlider setValue:currentSecond animated:YES];
        NSString *timeString = [self convertTime:currentSecond];
        self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",timeString,_totalTime];
    }];
}

- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    return _dateFormatter;
}


- (void)updateVideoSlider:(CGFloat)currentSecond {
    [self.videoSlider setValue:currentSecond animated:YES];
}

- (void)customVideoSlider:(CMTime)duration {
    self.videoSlider.maximumValue = CMTimeGetSeconds(duration);
    UIGraphicsBeginImageContextWithOptions((CGSize){ 1, 1 }, NO, 0.0f);
    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [self.videoSlider setMinimumTrackImage:transparentImage forState:UIControlStateNormal];
    [self.videoSlider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];
}



- (void)videoSlierChangeValue:(id)sender {
    UISlider *slider = (UISlider *)sender;
    NSLog(@"value change:%f",slider.value);
    
    if (slider.value == 0.000000) {
        
        [self.playView.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
            [self.playView.player play];
        }];
    }
}

- (void)videoSlierChangeValueEnd:(id)sender {
    UISlider *slider = (UISlider *)sender;
    NSLog(@"value end:%f",slider.value);
    CMTime changedTime = CMTimeMakeWithSeconds(slider.value, 1);
    
    
    [self.playView.player seekToTime:changedTime completionHandler:^(BOOL finished) {
        [self.playView.player play];
        [self.stateButton setTitle:@"Stop" forState:UIControlStateNormal];
    }];
}


- (void)dealloc
{
    
    [self.playerItem removeObserver:self forKeyPath:@"status" context:nil];
    [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    [self.playView.player removeTimeObserver:self.playbackTimeObserver];
    [super dealloc];
}




/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
